package nature.nano.control.script.assembly;

import java.util.ArrayList;
import java.util.List;

import nature.nano.component.PrimaryAccepter;
import nature.nano.component.Strings;
import nature.nano.iface.Props;
import nature.nano.iface.secondary.Startable;
import nature.nano.iface.secondary.Stoppable;

public class Controller extends PrimaryAccepter {
	
	private List<Startable> starters = new ArrayList<Startable>();
	private List<Stoppable> stoppers = new ArrayList<Stoppable>();
	
	private boolean stopping = false;
	
	public void addStarters(Startable... starters) {
		for (Startable starter : starters) {
			this.starters.add(starter);
		}
	}
	
	public void addStoppers(Stoppable... stoppers) {
		for (Stoppable stopper : stoppers) {
			this.stoppers.add(stopper);
		}
	}
	
	@Override
	public void onBegin(String type, Props props) {
		if (type.equals(Strings.error)) {
			stop();
		}
	}

	public void start() {
		for (Startable starter : starters) {
			if (stopping && starter instanceof ScriptAssembly) {
				continue;
			}
			starter.start();
		}
	}

	public void clear() {
		starters.clear();
		stoppers.clear();
		stopping = false;
	}
	
	private void stop() {
		stopping = true;
		for (int i = stoppers.size() - 1; i >= 0; --i) {
			stoppers.get(i).stop();
		}
	}
	
}
